﻿using System;
using Common;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;

namespace Extensions.Services;

public static class AddHealthCheck
{
    public static IServiceCollection AddHealthCheckSetup(this IServiceCollection service)
    {
        ArgumentNullException.ThrowIfNull(service);
        var hcBuilder = service.AddHealthChecks();
        // 自定义健康检查 （还可以继承接口的方式 来扩展 这里简单的扩展一下）
        hcBuilder.AddCheck("self", () => HealthCheckResult.Healthy());

        if (Appsettings.app("ConnectionStrings", "SqlServerEnable").ToBool())
        {
            var connectionString = Appsettings.app("ConnectionStrings", "ConnectionString");
            hcBuilder.AddSqlServer(connectionString, 
                timeout: TimeSpan.FromSeconds(5));
        }

        if (Appsettings.app("Redis", "Enable").ToBool())
        {
            var address = Appsettings.app("Redis", "RedisConnectionString");
            var pwd = Appsettings.app("Redis", "Password");
            if (!string.IsNullOrWhiteSpace(pwd))
            {
                address = string.Concat(address, ",password=", pwd);
            }
            hcBuilder.AddRedis(address, name: "redis-check", 
                tags: new[] { "redis" }, 
                timeout: TimeSpan.FromSeconds(10));
        }

        if (Appsettings.app("RabbitMQ", "Enable").ToBool())
        {
            // 默认检测的 hostname和这个地址 上的5672端口和/ 这个默认的虚拟机 账号密码都是guest guest如果rabbitmq中没有  那么就要自己创建
            var hostName = Appsettings.app("RabbitMQ", "HostName");
            hcBuilder.AddRabbitMQ($"amqp://{hostName}",name: "rabbitmq-check", 
                tags: new[] { "rabbitmq" }, 
                timeout: TimeSpan.FromSeconds(10));
        }

        return service;
    }
}